import {createRouter, createWebHashHistory} from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import cacheFactory, {CacheType} from "@/utils/cache/cache-factory";
import LoginStore, {setupStore} from "@/store/login/login-store";
import loginStore from "@/store/login/login-store";

const routes:RouteRecordRaw[] = [
    {
        path: "/login",
        name: "Login",
        component: () => import("@v/login/login.vue")
    },
    {
        path: "/",
        name: "Home",
        component: () => import("@v/home/home.vue"),
        children: [
            {
                path: "/:w+",
                name: "404",
                component: () => import("@v/404.vue")
            }
        ]
    }
]

const router = createRouter({
    routes,
    history: createWebHashHistory()
})

router.beforeEach(async (to) => {
    const store =  loginStore()
    if (!store.isRefresh){
        await setupStore();
        return to.fullPath;
    }
    if (to.path != '/login'){
         const tokenInfo = cacheFactory.instance(CacheType.LOCAL_STORAGE)?.getCache("tokenInfo")
         if (!tokenInfo){
             return "/login";
         }
    }else{
        const tokenInfo = cacheFactory.instance(CacheType.LOCAL_STORAGE)?.getCache("tokenInfo")
        if (tokenInfo){
            return "/";
        }
    }

})

export default router
